package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-05-21 17:13
 */
public class 题库_0034_在排序数组中查找元素的第一个和最后一个位置 {

  static
  class Solution {
    public int[] searchRange(int[] nums, int target) {
      if (nums == null || nums.length == 0) {
        return new int[] {-1, -1};
      }
      int left = 0;
      int right = nums.length - 1;
      while (left <= right) {
        int middle = (left + right) / 2;
        if (nums[middle] < target) {
          left = middle + 1;
        } else {
          right = middle - 1;
        }
      }
      int start = left;

      left = 0;
      right = nums.length - 1;
      while (left <= right) {
        int middle = (left + right) / 2;
        if (nums[middle] > target) {
          right = middle - 1;
        } else {
          left = middle + 1;
        }
      }
      int end = right;

      return start <= end ? new int[] {start, end} : new int[] {-1, -1};
    }
  }

}
